﻿using System;
using System.Linq;
using System.Web.Mvc;

using MiniSched.Data;

namespace MiniSched.Web.Controllers {
 
    public class HomeController : Controller {
    
        [HttpGet]
        public ActionResult Index(bool? subscribed) {            
            ViewBag.Subscribed = subscribed.HasValue && subscribed.Value;
            return View();
        }

        [HttpPost]
        public ActionResult Subscribe(string subscriber) {

            using (var context = new MiniSchedContext()) {

                var c = context;
                var messageType = MarketMessage.Announcements;

                var emailAddresses = c.EmailAddresses;
                var emailAddress = emailAddresses.FirstOrDefault(a => a.Address == subscriber);
                if (emailAddress == null) {
                    emailAddresses.Add(emailAddress = new EmailAddress {
                        Address = subscriber
                    });
                    context.SaveChanges();
                }

                var marketMessages = c.MarketMessages;
                var marketMessage = marketMessages.FirstOrDefault(m => m.OptionName == messageType);
                if (marketMessage == null) {
                    marketMessages.Add(marketMessage = new MarketMessage {
                        OptionName = messageType
                    });
                    context.SaveChanges();
                }

                var marketMessageSubscriptions = c.MarketMessageSubscriptions;
                var marketMessageSubscription = marketMessageSubscriptions.FirstOrDefault(s =>
                    (s.EmailAddressId == emailAddress.Id) &&
                    (s.MarketMessageId == marketMessage.Id)
                );
                if (marketMessageSubscription == null) {
                    marketMessageSubscriptions.Add(marketMessageSubscription = new MarketMessageSubscription {
                        EmailAddressId = emailAddress.Id,
                        MarketMessageId = marketMessage.Id
                    });
                    context.SaveChanges();
                }
            }

            return RedirectToAction("Index", new { subscribed = true });
        }
    }
}